package baseFx.common.utils;

import java.io.*;

public class FileUtils {
    /**
     * 获取文件后缀
     */
    public static String getExt(String filename) {
        if (filename == null || filename.endsWith(".")) {
            return "";
        }
        int idx = filename.lastIndexOf(".");
        if (idx > 0) {
            return filename.substring(idx);
        }
        return "";
    }

    /**
     * 合并路径
     */
    public static String combine(String... items) {
        return String.join(File.separator, items);
    }

    public static void copy(File src, File dest) {
        if (src.exists() == false) {
            throw new RuntimeException("源文件不存在");
        }
        if (dest.exists()) {
            throw new RuntimeException("目标文件已存在");
        }
        if (dest.getParentFile().exists() == false) {
            dest.getParentFile().mkdirs();
        }
        try {
            dest.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException("文件创建失败", e);
        }
        try (InputStream is = new FileInputStream(src)) {
            try (OutputStream os = new FileOutputStream(dest)) {
                byte[] data = new byte[4096];
                int len;
                while ((len = is.read(data, 0, data.length)) > 0) {
                    os.write(data, 0, len);
                }
                os.flush();
            } catch (Exception e) {
                throw new RuntimeException("数据写入失败", e);
            }
        } catch (IOException e) {
            throw new RuntimeException("数据读取失败", e);
        }
    }
}
